package com.ncloud.timetask.dashboard.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.timetask.dashboard.mapper.DashboardSaleTaskMapper;
import com.ncloud.timetask.dashboard.service.DashboardSaleTaskService;

/**
 * @author sundelong
 * project_name: timetask 
 * type_name: DashboardSaleTaskServiceImpl 
 * date: 2017年6月21日下午4:02:08 
 * 
 */
@Service
public class DashboardSaleTaskServiceImpl implements DashboardSaleTaskService {
	
	@Autowired
	DashboardSaleTaskMapper saleMapper;
	
	@Override
	public void insertSaleCount(String taskId) {
		List<Map<Object,Object>> countList=new ArrayList<Map<Object,Object>>();
		try {				
			countList=saleMapper.getSlaeCountMonth();
			String year = ThisMonth().get("year");
			String month = ThisMonth().get("month");
			String remark = null;
			for(int i=0;i<countList.size();i++){
				Map<Object,Object> map=new HashMap<Object, Object>();
				map=countList.get(i);
				String saleId=map.get("user_id").toString();
				boolean flag=map.containsKey("fee");
				String saleCount = null;
				if(flag){
					saleCount=map.get("fee").toString();
					}
				
				//判断这个月份的数据有没有插入表中，如果已插入就更新数据，没有就插入；
				int count = saleMapper.getExistence(taskId, year, month,saleId);
				if(count == 0){
					saleMapper.insertSaleCount(taskId, year, month, saleId, saleCount, remark);
				}else{
					saleMapper.updateSaleCount(saleCount, taskId, year, month, saleId);
				}
			}
									
		} catch (Exception e) {
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
	}
	
	public Map<String,String> LastMonth(){
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -1);
		SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		String time = format.format(cal.getTime());
		String year = time.split("-")[0];
		String day = time.split("-")[1];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",day);
		return dateMap;		
	}
	public Map<String, String> ThisMonth(){
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String time = sdf.format(date);
		String year = time.split("-")[0];
		String day = time.split("-")[1];
		Map<String,String> dateMap = new HashMap<String, String>();
		dateMap.put("year", year);
		dateMap.put("month",day);
		return dateMap;		
	}

}
